package com.adam.blog.service.impl;

import com.adam.blog.dao.dos.Archives;
import com.adam.blog.dao.mapper.ArticleBodyMapper;
import com.adam.blog.dao.mapper.ArticleMapper;
import com.adam.blog.dao.mapper.ArticleTagMapper;
import com.adam.blog.dao.pojo.Article;
import com.adam.blog.dao.pojo.ArticleBody;
import com.adam.blog.dao.pojo.ArticleTag;
import com.adam.blog.dao.pojo.SysUser;
import com.adam.blog.service.*;
import com.adam.blog.utils.UserThreadLocal;
import com.adam.blog.vo.ArticleBodyVo;
import com.adam.blog.vo.ArticleVo;
import com.adam.blog.vo.Result;
import com.adam.blog.vo.TagVo;
import com.adam.blog.vo.params.ArticleParams;
import com.adam.blog.vo.params.PageParams;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ThreadService threadService;
    @Autowired
    private ArticleTagMapper articleTagMapper;

    /**
     * 分页查询article数据库表
     * @param pageParams
     * @return
     */
    @Override
    public List<ArticleVo> listArticle(PageParams pageParams) {
         Page<Article> page =new Page<>(pageParams.getPage(),pageParams.getPageSize());

        IPage<Article> articleIPage = articleMapper.listArticle(page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        //分页记录
        List<Article> records = articleIPage.getRecords();
        return copyList(records,true,true);
    }

//    @Override
//    public List<ArticleVo> listArticle(PageParams pageParams) {
//        //分页设置
//        Page<Article> page =new Page<>(pageParams.getPage(),pageParams.getPageSize());
//        //查询条件可以用这个设定
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        //如果需要根据分类id查询
//        if(pageParams.getCategoryId() != null){
//            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
//        }
//        //如果需要根据标签id查询
//        List<Long> articleList = new ArrayList<>();
//        if(pageParams.getTagId() != null){
//            //article_tag   tag_id : article_id
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
//            //获取标签id下的所有articleTags
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                //获取标签id下的所有文章id
//                articleList.add(articleTag.getArticleId());
//            }
//            if(articleList.size() > 0){
//                //and id in {*,*,*}
//                queryWrapper.in(Article::getId,articleList);
//            }
//        }
//        /**
//         * 1.是否进行置顶排序
//         * 2.order by createDate
//         */
//        queryWrapper.orderByDesc(Article::getWeight,Article::getCreateDate);
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//        List<Article> records = articlePage.getRecords();
//        //不直接通过pojo返回，通过vo对象返回
//        List<ArticleVo> articleVoList = copyList(records,true,true);
//
//        return articleVoList;
//    }

    @Override
    public List<ArticleVo> hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle);
        List<Article> articleList = articleMapper.selectList(queryWrapper);
        return copyList(articleList,false,false);
    }

    @Override
    public List<ArticleVo> newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId,Article::getTitle);
        List<Article> articleList = articleMapper.selectList(queryWrapper);
        return copyList(articleList,false,false);
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1.根据id查询文章信息
         * 2.根据bodyId 和 categoryId 关联查询
         */

        Article article = articleMapper.selectById(articleId);
        ArticleVo articleVo = copy(article,true,true,true,true);
        //查看文章内容后 增加浏览量 使用线程池，多线程进行 避免更新操作接口的耗时影响主操作
        //线程池 可以把更新操作放到线程池中执行 与主线程不相关
        threadService.updateArticleViewCount(articleMapper,article);

        return Result.success(articleVo);
    }

    @Override
    public Result publish(ArticleParams articleParams) {
        SysUser sysUser = UserThreadLocal.get();
        /**
         * 1.发布文章 目的是构建Article对象
         * 2.作者id   当前登录用户  此接口加入登录拦截器
         * 3.标签     将标签加入关联列表当中
         * 4.body 内容存储articleBody id
         */
        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setCommentCounts(0);
        article.setTitle(articleParams.getTitle());
        article.setSummary(articleParams.getSummary());
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(articleParams.getCategory().getId());
        //插入article表中   获得文章id
        articleMapper.insert(article);

        List<TagVo> tags = articleParams.getTags();
        if(tags != null){
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(articleId);
                articleTag.setTagId(tag.getId());
                articleTagMapper.insert(articleTag);
            }
        }

        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        articleBody.setContent(articleParams.getBody().getContent());
        articleBody.setContentHtml(articleParams.getBody().getContentHtml());
        articleBodyMapper.insert(articleBody);
        article.setBodyId(articleBody.getId());

        articleMapper.updateById(article);

        //另一种传输数据方式，不使用vo，使用map键值对
        Map<String,String> map = new HashMap<>();
        map.put("id",article.getId().toString());

        return Result.success(map);
    }

    /**
     * 复制列表，将pojo对象复制成vo对象
     * @param records
     * @param isTag
     * @param isAuthor
     * @return
     */
    private List<ArticleVo>copyList(List<Article> records,boolean isTag,boolean isAuthor) {
        ArrayList<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleVoList;
    }
    private List<ArticleVo>copyList(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        ArrayList<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    public ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory){
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);
//        Long id = article.getId();
//        @JsonSerialize(using = ToStringSerializer.class)
//        articleVo.setId(id);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));;
        //并不是所有接口都需要标签、作者信息
        if(isTag){
            Long articleId = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(articleId));
        }
        if(isAuthor){
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        if(isBody){
            Long bodyId = article.getBodyId();
            articleVo.setBody((findArticleBodyById(bodyId)));
        }
        if(isCategory){
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(categoryService.findCategoryById(categoryId));
        }
        return articleVo;
    }

    private ArticleBodyVo findArticleBodyById(Long bodyId) {
        ArticleBody articleBody = articleBodyMapper.selectById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
